//https://leetcode.cn/problems/maximum-product-of-two-elements-in-an-array/solutions/1774263/shu-zu-zhong-liang-yuan-su-de-zui-da-che-oqkf/

#include <iostream>
#include <vector>
#include <limits>
using namespace std;

int maxProduct(const std::vector<int>& nums) {
    int n = nums.size();
    if (n < 2) {
        throw std::invalid_argument("数组长度至少为2");
    }

    int max1 = std::numeric_limits<int>::min();
    int max2 = std::numeric_limits<int>::min();
    int min1 = std::numeric_limits<int>::max();
    int min2 = std::numeric_limits<int>::max();

    for (int num : nums) {
        if (num > max1) {
            max2 = max1;
            max1 = num;
        } else if (num > max2) {
            max2 = num;
        }

        if (num < min1) {
            min2 = min1;
            min1 = num;
        } else if (num < min2) {
            min2 = num;
        }
    }

    return std::max(max1 * max2, min1 * min2);
};

class Solution {
public:
    int maxProduct(vector<int>& nums) {
        int a = nums[0], b = nums[1];
        if (a < b) {
            swap(a, b);
        }
        for (int i = 2; i < nums.size(); i++) {
            if (nums[i] > a) {
                b = a;
                a = nums[i];
            } else if (nums[i] > b) {
                b = nums[i];
            }
        }
        return (a - 1) * (b - 1);
    }
};